package com.bringspring.system.permission.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bringspring.common.base.DataFieldType;
import com.bringspring.common.base.SearchMethodEnum;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.database.model.DataSourceModel;
import com.bringspring.common.database.model.dto.PreparedStatementDTO;
import com.bringspring.common.database.sql.SqlBase;
import com.bringspring.common.database.util.ConnUtil;
import com.bringspring.common.database.util.DbTypeUtil;
import com.bringspring.common.database.util.JdbcUtil;
import com.bringspring.common.util.*;
import com.bringspring.common.util.treeutil.ListToTreeUtil;
import com.bringspring.common.util.treeutil.SumTree;
import com.bringspring.common.util.treeutil.newtreeutil.TreeDotUtils;
import com.bringspring.system.base.entity.*;
import com.bringspring.system.base.model.button.ButtonModel;
import com.bringspring.system.base.model.column.ColumnModel;
import com.bringspring.system.base.model.form.ModuleFormModel;
import com.bringspring.system.base.model.module.ModuleModel;
import com.bringspring.system.base.model.resource.ResourceModel;
import com.bringspring.system.base.service.*;
import com.bringspring.system.base.util.UserAuthAreaUtils;
import com.bringspring.system.permission.constant.AuthorizeConst;
import com.bringspring.system.permission.entity.AuthorizeEntity;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.entity.UserRelationEntity;
import com.bringspring.system.permission.mapper.AuthorizeMapper;
import com.bringspring.system.permission.model.authorize.*;
import com.bringspring.system.permission.service.*;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 操作权限
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月26日 上午9:18
 */
@Slf4j
@Service
@DSTransactional
public class AuthorizeServiceImpl extends ServiceImpl<AuthorizeMapper, AuthorizeEntity> implements AuthorizeService {

    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private DataSourceModel dataSourceUtils;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PositionService positionService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private ModuleService moduleService;
    @Autowired
    private ModuleButtonService buttonService;
    @Autowired
    private ModuleColumnService columnService;
    @Autowired
    private ModuleFormService formService;
    @Autowired
    private ModuleDataAuthorizeSchemeService schemeService;

    @Override
    public AuthorizeVO getAuthorize(boolean isCache) {
        // 是否从缓冲里面获取权限
        if (isCache) {
            return getCacheAuthor(userProvider.get());
        } else {
            return getAuthorize(userProvider.get());
        }
    }

    private AuthorizeVO getCacheAuthor(UserInfo userInfo) {
        // 是否从缓冲里面获取权限
        String cacheKey = cacheKeyUtil.getUserAuthorize() + userInfo.getUserId();
        if (!redisUtil.exists(cacheKey)) {
            AuthorizeVO authorizeModel = getAuthorize(userInfo);
            if (authorizeModel.getModuleList().size() != 0) {
                redisUtil.insert(cacheKey, authorizeModel, 60);
            }
            return authorizeModel;
        } else {
            return JsonUtil.getJsonToBean(redisUtil.getString(cacheKey).toString(), AuthorizeVO.class);
        }
    }


    @Override
    public AuthorizeVO getAuthorize(UserInfo userInfo) {
        List<ModuleModel> moduleList = new ArrayList<>();
        List<ButtonModel> buttonList = new ArrayList<>();
        List<ColumnModel> columnList = new ArrayList<>();
        List<ResourceModel> resourceList = new ArrayList<>();
        List<ModuleFormModel> formsList = new ArrayList<>();
        Boolean isAdmin = userInfo.getIsAdministrator();
        if (!isAdmin) {
            List<String> roleIds = new ArrayList<>();
            roleService.getRoleIdsByCurrentUser(userInfo.getDepartmentId()).forEach(role -> {
                //判断角色状态是否为有效，显示当前组织内角色的并集
                if (role != null) {
                    roleIds.add("'" + role + "'");
                }
            });
            if (roleIds.size() != 0) {
                String roleIdsStr = String.join(",", roleIds);
                moduleList = this.baseMapper.findModule(roleIdsStr);
                buttonList = this.baseMapper.findButton(roleIdsStr);
                columnList = this.baseMapper.findColumn(roleIdsStr);
                resourceList = this.baseMapper.findResource(roleIdsStr);
                formsList = this.baseMapper.findForms(roleIdsStr);
            }

        } else {
            moduleList = this.baseMapper.findModuleAdmin(1);
            buttonList = this.baseMapper.findButtonAdmin(1);
            columnList = this.baseMapper.findColumnAdmin(1);
            resourceList = this.baseMapper.findResourceAdmin(1);
            formsList = this.baseMapper.findFormsAdmin(1);
        }
        return new AuthorizeVO(moduleList, buttonList, columnList, resourceList, formsList);
    }

    @Override
    public AuthorizeVO getAuthorizeByRoleId(String roleId) {
        List<ModuleModel> moduleList = new ArrayList<>();
        List<ButtonModel> buttonList = new ArrayList<>();
        List<ColumnModel> columnList = new ArrayList<>();
        List<ResourceModel> resourceList = new ArrayList<>();
        List<ModuleFormModel> formsList = new ArrayList<>();

        moduleList = this.baseMapper.findModule(roleId);
        buttonList = this.baseMapper.findButton(roleId);
        columnList = this.baseMapper.findColumn(roleId);
        resourceList = this.baseMapper.findResource(roleId);
        formsList = this.baseMapper.findForms(roleId);


        return new AuthorizeVO(moduleList, buttonList, columnList, resourceList, formsList);
    }

    @Override
    public void save(String objectId, AuthorizeDataUpForm authorizeList) {
        SaveBatchForm form = JsonUtil.getJsonToBean(authorizeList, SaveBatchForm.class);
        form.setRoleIds(new String[]{objectId});
        this.saveBatch(form, false);
    }

    @Override
    public void saveBatch(SaveBatchForm saveBatchForm, boolean isBatch) {
        try {
            UserInfo userInfo = userProvider.get();
            String dbName = userInfo.getTenantDbConnectionString() == null ?
                    dataSourceUtils.getDbName() : userInfo.getTenantDbConnectionString();

            List<AuthorizeEntity> objectList = new ArrayList<>();
            List<AuthorizeEntity> authorizeList = new ArrayList<>();
            // 设置权限归属对象
            setEntity(saveBatchForm.getUserIds(), AuthorizeConst.USER, objectList, true);
            setEntity(saveBatchForm.getPositionIds(), AuthorizeConst.POSITION, objectList, true);
            setEntity(saveBatchForm.getRoleIds(), AuthorizeConst.ROLE, objectList, true);
            // 设置权限模块
            setEntity(saveBatchForm.getButton(), AuthorizeConst.BUTTON, authorizeList, false);
            setEntity(saveBatchForm.getModule(), AuthorizeConst.MODULE, authorizeList, false);
            setEntity(saveBatchForm.getColumn(), AuthorizeConst.COLUMN, authorizeList, false);
            setEntity(saveBatchForm.getResource(), AuthorizeConst.RESOURCE, authorizeList, false);
            setEntity(saveBatchForm.getForm(), AuthorizeConst.FROM, authorizeList, false);

            @Cleanup Connection conn = ConnUtil.getConn(dataSourceUtils, dbName);

            // 删除角色相关信息
            List<String> objectIdAll = objectList.stream().map(AuthorizeEntity::getObjectId).collect(Collectors.toList());
            userService.delCurRoleUser(objectIdAll);
            if (!isBatch) {
                JdbcUtil.creUpDe(new PreparedStatementDTO(conn, XSSEscape.escapeEmpty(SqlBase.getAuthorDelSql(objectIdAll))));
            }

            // 插入数据
            String sql = DbTypeUtil.checkOracle(dataSourceUtils) || DbTypeUtil.checkPostgre(dataSourceUtils) ?
                    SqlBase.INSERT_AUTHORIZE2 : SqlBase.INSERT_AUTHORIZE;
            List<PreparedStatementDTO> prepareDtoList = new LinkedList<>();
            for (int i = 0; i < objectList.size(); i++) {
                for (AuthorizeEntity entityItem : authorizeList) {
                    LinkedList<Object> paramList = new LinkedList<>();
                    paramList.add(RandomUtil.uuId());
                    paramList.add(entityItem.getItemType());
                    paramList.add(entityItem.getItemId());
                    paramList.add(objectList.get(i).getObjectType());
                    paramList.add(objectList.get(i).getObjectId());
                    paramList.add(i);
                    paramList.add(DateUtil.getNow());
                    paramList.add(userInfo.getUserId());
                    prepareDtoList.add(new PreparedStatementDTO(null, null, paramList));
                }
            }
            JdbcUtil.creUpDeBatchOneSql(conn, sql, prepareDtoList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("权限报错:" + e.getMessage());
        }
    }

    /**
     * 权限
     */
    private void setEntity(String[] ids, String type, List<AuthorizeEntity> entityList, Boolean objectFlag) {
        if (ids != null) {
            for (String id : ids) {
                AuthorizeEntity entity = new AuthorizeEntity();
                if (objectFlag) {
                    entity.setObjectType(type);
                    entity.setObjectId(id);
                } else {
                    entity.setItemType(type);
                    entity.setItemId(id);
                }
                entityList.add(entity);
            }
        }
    }

    @Override
    public List<AuthorizeEntity> getListByUserId(boolean isAdmin, String userId) {
        if (!isAdmin) {
            QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserRelationEntity::getUserId, userId);
            List<UserRelationEntity> list = userRelationService.list(queryWrapper);
            List<String> userRelationList = list.stream().map(u -> u.getObjectId()).collect(Collectors.toList());
            userRelationList.add(userId);
            QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(AuthorizeEntity::getObjectId, userRelationList);
            return this.list(wrapper);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<AuthorizeEntity> getListByObjectId(String objectId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
        return this.list(queryWrapper);
    }

    @Override
    public Boolean existByObjId(String objectId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, "module");
        return this.count(queryWrapper) > 0;
    }

    @Override
    public List<AuthorizeEntity> getListByObjectId(String objectId, String itemType) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, itemType);
        return this.list(queryWrapper);
    }

    @Override
    public List<AuthorizeEntity> getListByObjectAndItem(String itemId, String objectType) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectType, objectType).eq(AuthorizeEntity::getItemId, itemId);
        return this.list(queryWrapper);
    }

    @Override
    public List<AuthorizeEntity> getListByItemId(String itemId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemId, itemId);
        return this.list(queryWrapper);
    }

    @Override
    public void saveAuth(String itemId, SaveAuthForm saveAuthForm) {
        String creatorUserId = userProvider.get().getUserId();
        List<AuthorizeEntity> list = new ArrayList<>();
        for (int i = 0; i < saveAuthForm.getObjectId().length; i++) {
            AuthorizeEntity authorizeEntity = new AuthorizeEntity();
            authorizeEntity.setId(RandomUtil.uuId());
            authorizeEntity.setItemType("portal");
            authorizeEntity.setItemId(itemId);
            authorizeEntity.setObjectType(saveAuthForm.getObjectType());
            authorizeEntity.setObjectId(saveAuthForm.getObjectId()[i]);
            authorizeEntity.setSortCode(Long.valueOf(i));
            authorizeEntity.setCreatorTime(new Date());
            authorizeEntity.setCreatorUserId(creatorUserId);
            list.add(authorizeEntity);
        }
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemId, itemId);
        this.remove(queryWrapper);
        if (list.size() > 0) {
            this.saveBatch(list);
        }
    }

    /**
     * 获取条件过滤
     *
     * @param conditionModel 权限信息
     * @return
     */
    @Override
    public QueryWrapper<T> getCondition(AuthorizeConditionModel conditionModel) {
        Object obj = conditionModel.getObj();
        String moduleId = conditionModel.getModuleId();
        String tableName = conditionModel.getTableName();
        UserInfo userInfo = userProvider.get();
        QueryWrapper<T> queryWhere = (QueryWrapper<T>) obj;
        AuthorizeVO model = this.getAuthorize(true);
        List<ResourceModel> resourceList = model.getResourceList().stream().filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
        if (resourceList.size() == 0) {
            return null;
        }
        List<ResourceModel> resourceList1 = new ArrayList<>();
        //拼接计数
        int t = 0;
        for (ResourceModel item : resourceList) {
            if ("alldata".equals(item.getEnCode())) {
                t = 0;
                break;
            }
            List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
            for (int i = 0; i < conditionModelList.size(); i++) {
                ConditionModel conditionItem = conditionModelList.get(i);
                for (int k = 0; k < conditionItem.getGroups().size(); k++) {
                    ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
                    String itemValue = fieldItem.getValue();
                    String itemMethod = fieldItem.getOp();
                    String itemTable = fieldItem.getBindTable();
                    if (StringUtils.isNotEmpty(itemTable) && itemTable.equalsIgnoreCase(tableName)) {
                        resourceList1.add(item);
                    }
                    if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)
                            || AuthorizeConditionEnum.COMPANY.getCondition().equals(itemValue)
                            || AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)
                            || AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)
                            || AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)
                            || itemMethod.equals(SearchMethodEnum.Equal.getMessage())
                            || itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())
                            || itemMethod.equals(SearchMethodEnum.LessThan.getMessage())
                            || itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())
                            || itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())
                            || itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())
                            || itemMethod.equals(SearchMethodEnum.Include.getMessage())
                    ) { //当前用户Id
                        t = 1;
                    }
                }
            }
        }
        AtomicBoolean flag = new AtomicBoolean(true);
        if (t == 1) {
            if (resourceList1.size() > 0) {
                queryWhere.and(tw -> {
                    for (ResourceModel item : resourceList1) {
                        List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
                        for (int i = 0; i < conditionModelList.size(); i++) {
                            ConditionModel conditionItem = conditionModelList.get(i);
                            for (int k = 0; k < conditionItem.getGroups().size(); k++) {
                                ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
                                String itemField = fieldItem.getField();
                                String itemValue = fieldItem.getValue();
                                String itemMethod = fieldItem.getOp();
                                if ("and".equalsIgnoreCase(conditionItem.getLogic())) {
                                    if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)) { //当前用户
                                        tw.eq(itemField, userInfo.getUserId());
                                    } else if (AuthorizeConditionEnum.COMPANY.getCondition().equals(itemValue)) { //当前公司
                                        String orgId = userInfo.getOrganizeId();
                                        tw.eq(itemField, orgId);
                                    } else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)) { //当前组织
                                        String orgId = userInfo.getOrganizeId();
                                        if (StringUtils.isNotEmpty(userInfo.getDepartmentId())) {
                                            orgId = userInfo.getDepartmentId();
                                        }
                                        tw.eq(itemField, orgId);
                                    } else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)) { //组织及子组织
                                        String orgId = userInfo.getOrganizeId();
                                        if (StringUtils.isNotEmpty(userInfo.getDepartmentId())) {
                                            orgId = userInfo.getDepartmentId();
                                        }
                                        List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
                                        underOrganizations.add(orgId);
                                        tw.in(itemField, underOrganizations);
                                    } else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)) { //用户及用户下属
                                        List<String> idsList = new ArrayList<>();
                                        if (userInfo.getSubordinateIds().size() > 0) {
                                            idsList = userInfo.getSubordinateIds();
                                        }
                                        idsList.add(userInfo.getUserId());
                                        tw.in(itemField, idsList);
                                    } else if (AuthorizeConditionEnum.AUTH_AREA_USER.getCondition().equals(itemValue)) { //授权区域内的人员
                                        List<String> searchUserIdList = UserAuthAreaUtils.getHaveSameAuthAreaAndRoleTypeWithMe();
                                        if (CollectionUtil.isEmpty(searchUserIdList)) {
                                            flag.set(false);
                                            break;
                                        }
                                        tw.in(itemField, searchUserIdList);

                                    } else if (AuthorizeConditionEnum.AUTH_AREA_CUSTOMER.getCondition().equals(itemValue)) { //授权区域内客户
                                        List<UserRelationEntity> arealist = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, userInfo.getUserId()));
                                        if (CollectionUtil.isEmpty(arealist)) {
                                            flag.set(false);
                                            break;
                                        }
                                        List<String> authAreaIdList = arealist.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
                                        List<List<String>> address = CollectionUtil.list(false);
                                        for (String str : authAreaIdList) {
                                            String[] split = str.replace("\"", "").replace("[", "").replace("]", "").split(",");
                                            List<String> list = Arrays.asList(split);
                                            address.add(list);
                                        }
                                        if (CollectionUtil.isNotEmpty(address)) {
                                            address.stream().filter(x -> {
                                                boolean flag1 = x.size() < 2 && x.get(0).equals("10");
                                                return !flag1;
                                            }).collect(Collectors.toList());
                                            if (address.size() < 2 && address.get(0).equals("10")) {
                                                flag.set(false);
                                                break;
                                            }
                                        }
                                        tw.and((x -> {
                                            for (List<String> ll : address) {
                                                List<String> addressList = JsonUtil.getJsonToList(ll, String.class);
                                                if (addressList.size() > 1) {
                                                    String collect = addressList.stream().map((s) -> "\"" + s + "\"").collect(Collectors.joining(","));
                                                    collect = "[" + collect;
                                                    x.or().like(itemField, collect);
                                                } else {
                                                    String s = addressList.get(addressList.size() - 1);
                                                    s = "[" + "\"" + s + "\"";
                                                    x.or().like(itemField, s);
                                                }
                                            }
                                        }));
                                    } else if (AuthorizeConditionEnum.Include.getCondition().equals(itemMethod)) { //选择公司和部门 包含
//                                        去除其他字符
                                        String replace = itemValue.replace('[', ' ').replace(']', ' ').replace('"', ' ').replaceAll(" ", "");
                                        List<String> finalIdsList = Arrays.asList(replace.split(","));
                                        tw.in(itemField, finalIdsList);
                                    } else {//任意文本
                                        if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
                                            tw.eq(itemField, itemValue);
                                        } else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
                                            tw.ne(itemField, itemValue);
                                        } else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
                                            tw.lt(itemField, itemValue);
                                        } else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
                                            tw.le(itemField, itemValue);
                                        } else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
                                            tw.gt(itemField, itemValue);
                                        } else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
                                            tw.ge(itemField, itemValue);
                                        }
                                    }
                                } else {
                                    if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)) { //当前用户
                                        tw.or(
                                                qw -> qw.eq(itemField, userInfo.getUserId())
                                        );
                                    } else if (AuthorizeConditionEnum.COMPANY.getCondition().equals(itemValue)) { //当前公司
                                        String orgId = userInfo.getOrganizeId();
                                        String finalOrgId = orgId;
                                        tw.or(
                                                qw -> qw.eq(itemField, finalOrgId)
                                        );
                                    } else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)) { //当前组织
                                        String orgId = userInfo.getOrganizeId();
                                        if (StringUtils.isNotEmpty(userInfo.getDepartmentId())) {
                                            orgId = userInfo.getDepartmentId();
                                        }
                                        String finalOrgId = orgId;
                                        tw.or(
                                                qw -> qw.eq(itemField, finalOrgId)
                                        );
                                    } else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)) { //组织及子组织
                                        String orgId = userInfo.getOrganizeId();
                                        if (StringUtils.isNotEmpty(userInfo.getDepartmentId())) {
                                            orgId = userInfo.getDepartmentId();
                                        }
                                        List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
                                        underOrganizations.add(orgId);
                                        tw.or(
                                                qw -> qw.in(itemField, underOrganizations)
                                        );
                                    } else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)) { //用户及用户下属
                                        List<String> idsList = new ArrayList<>();
                                        if (userInfo.getSubordinateIds().size() > 0) {
                                            idsList = userInfo.getSubordinateIds();
                                        }
                                        idsList.add(userInfo.getUserId());
                                        List<String> finalIdsList = idsList;
                                        tw.or(
                                                qw -> qw.in(itemField, finalIdsList)
                                        );
                                    } else if (AuthorizeConditionEnum.AUTH_AREA_USER.getCondition().equals(itemField)) { //授权区域里面的人
                                        List<String> authUserList = UserAuthAreaUtils.getHaveSameAuthAreaAndRoleTypeWithMe();
                                        if (CollectionUtil.isEmpty(authUserList)) {
                                            flag.set(false);
                                            break;
                                        }
                                        tw.or(qw -> qw.in(itemField, fieldItem));
                                    } else if (AuthorizeConditionEnum.AUTH_AREA_CUSTOMER.getCondition().equals(itemField)) {
                                        List<UserRelationEntity> arealist = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, userInfo.getUserId()));
                                        if (CollectionUtil.isEmpty(arealist)) {
                                            flag.set(false);
                                            break;
                                        }
                                        List<String> authAreaIdList = arealist.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
                                        List<List<String>> address = CollectionUtil.list(false);
                                        for (String str : authAreaIdList) {
                                            String[] split = str.replace("\"", "").replace("[", "").replace("]", "").split(",");
                                            List<String> list = Arrays.asList(split);
                                            address.add(list);
                                        }
                                        if (CollectionUtil.isNotEmpty(address)) {
                                            address.stream().filter(x -> {
                                                boolean flag1 = x.size() < 2 && x.get(0).equals("10");
                                                return !flag1;
                                            }).collect(Collectors.toList());
                                            if (address.size() < 2 && address.get(0).equals("10")) {
                                                flag.set(false);
                                                break;
                                            }
                                        }
                                        tw.or((x -> {
                                            for (List<String> ll : address) {
                                                List<String> addressList = JsonUtil.getJsonToList(ll, String.class);
                                                if (addressList.size() > 1) {
                                                    String collect = addressList.stream().map((s) -> "\"" + s + "\"").collect(Collectors.joining(","));
                                                    collect = "[" + collect;
                                                    x.or().like(itemField, collect);
                                                } else {
                                                    String s = addressList.get(addressList.size() - 1);
                                                    s = "[" + "\"" + s + "\"";
                                                    x.or().like(itemField, s);
                                                }
                                            }
                                        }));
                                    } else if (AuthorizeConditionEnum.Include.getCondition().equals(itemMethod)) { //选择公司和部门 包含
//                                        去除其他字符
                                        String replace = itemValue.replace('[', ' ').replace(']', ' ').replace('"', ' ').replaceAll(" ", "");
                                        List<String> finalIdsList = Arrays.asList(replace.split(","));
                                        tw.or(
                                                qw -> qw.in(itemField, finalIdsList)
                                        );
                                    } else {//任意文本
                                        if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
                                            tw.or(
                                                    qw -> qw.eq(itemField, itemValue)
                                            );
                                        } else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
                                            tw.or(
                                                    qw -> qw.ne(itemField, itemValue)
                                            );
                                        } else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
                                            tw.or(
                                                    qw -> qw.lt(itemField, itemValue)
                                            );
                                        } else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
                                            tw.or(
                                                    qw -> qw.le(itemField, itemValue)
                                            );
                                        } else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
                                            tw.or(
                                                    qw -> qw.gt(itemField, itemValue)
                                            );
                                        } else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
                                            tw.or(
                                                    qw -> qw.ge(itemField, itemValue)
                                            );
                                        }
                                    }
                                }
                            }

                        }
                    }
                });
            }
        }
        return queryWhere;
    }


    /**
     * 获取条件过滤
     *
     * @param userInfo  用户信息
     * @param moduleId  功能模块Id
     * @param tableName 主表名
     * @return
     */
    @Override
    public String getConditionSql(UserInfo userInfo, String moduleId, String tableName) {
        StringBuilder queryWhere = new StringBuilder();
        AuthorizeVO model = this.getAuthorize(true);
        List<ResourceModel> resourceList = model.getResourceList().stream().filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
        //方案
        for (ResourceModel item : resourceList) {
            if ("alldata".equals(item.getEnCode())) {
                StringBuilder allData = new StringBuilder();
                allData.append("alldata");
                queryWhere = allData;
                break;
            }
            StringBuilder itemWhere = new StringBuilder();
            List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
            //分组
            for (int i = 0; i < conditionModelList.size(); i++) {
                StringBuilder subWhere = new StringBuilder();
                ConditionModel conditionItem = conditionModelList.get(i);
                //条件
                for (int k = 0; k < conditionItem.getGroups().size(); k++) {
                    ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
                    if (conditionItem.getGroups().indexOf(fieldItem) > 0) {
                        subWhere.append(" " + conditionItem.getLogic().toUpperCase() + " ");
                    }
                    String itemField = fieldItem.getField();
                    if (!itemField.contains(".")) {
                        itemField = tableName + "." + itemField;
                    }
                    String itemValue = fieldItem.getValue();
                    String itemMethod = fieldItem.getOp();
                    //当前用户
                    if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)) {
                        subWhere.append(itemField + " = '" + userInfo.getUserId() + "' ");
                    }
                    //当前公司
                    else if (AuthorizeConditionEnum.COMPANY.getCondition().equals(itemValue)) {
                        String orgId = userInfo.getOrganizeId();
                        subWhere.append(itemField + " = '" + orgId + "' ");
                    }
                    //当前组织
                    else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)) {
                        String orgId = userInfo.getOrganizeId();
                        if (StringUtils.isNotEmpty(userInfo.getDepartmentId())) {
                            orgId = userInfo.getDepartmentId();
                        }
                        subWhere.append(itemField + " = '" + orgId + "' ");
                    }
                    //当前组织及子组织
                    else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)) {
                        String orgId = userInfo.getOrganizeId();
                        if (StringUtils.isNotEmpty(userInfo.getDepartmentId())) {
                            orgId = userInfo.getDepartmentId();
                        }
                        //获取子组织
                        List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
                        underOrganizations.add(orgId);
                        String organization = underOrganizations.stream()
                                .map(org -> "\'" + org + "\'")
                                .collect(Collectors.joining(","));
                        subWhere.append(itemField + " in( " + organization + " )" + " ");
                    }
                    //当前用户及下属
                    else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)) {
                        List<String> subOrganizeIds = new ArrayList<>();
                        if (userInfo.getSubordinateIds().size() > 0) {
                            subOrganizeIds = userInfo.getSubordinateIds();
                        }
                        subOrganizeIds.add(userInfo.getUserId());
                        String ids = subOrganizeIds.stream().map(id -> "\'" + id + "\'").collect(Collectors.joining(","));
                        subWhere.append(itemField + " in( " + ids + " )" + " ");
                    }
                    //任意文本
                    else {
                        if (fieldItem.getType().equals(DataFieldType.Varchar.getMessage())) {
                            itemValue = " \'" + itemValue + "\'";
                        }
                        if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
                            subWhere.append(itemField + " = " + itemValue);
                        } else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
                            subWhere.append(itemField + " <> " + itemValue);
                        } else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
                            subWhere.append(itemField + " < " + itemValue);
                        } else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
                            subWhere.append(itemField + " <= " + itemValue);
                        } else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
                            subWhere.append(itemField + " > " + itemValue);
                        } else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
                            subWhere.append(itemField + " >= " + itemValue);
                        }
                    }
                }
                if (subWhere.length() != 0) {
                    itemWhere.append(" AND (" + subWhere + ")");
                }
            }
            if (itemWhere.length() != 0) {
                queryWhere.append(itemWhere);
            }
        }
        return queryWhere.toString();
    }

    @Override
    public AuthorizeDataReturnVO getAuthorizeDataReturnVO(AuthorizeVO authorizeModel, List<AuthorizeEntity> list, DataValuesQuery dataValuesQuery, String objectId) {
        AuthorizeDataReturnVO dataReturnVO = new AuthorizeDataReturnVO();
        if (!StringUtils.isEmpty(dataValuesQuery.getType())) {
            switch (dataValuesQuery.getType()) {
                case "module":
                    List<ModuleEntity> moduleList = moduleService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    dataReturnVO = this.module(moduleList, list, authorizeModel);
                    return dataReturnVO;
                case "button":
                    List<ModuleEntity> moduleList1 = moduleService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList1 = new ArrayList<>();
                    if (!StringUtils.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId1 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList1 = moduleList1.stream().filter(t -> moduleId1.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleButtonEntity> moduleButtonList = buttonService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    dataReturnVO = this.moduleButton(selectList1, moduleButtonList, list, authorizeModel);
                    return dataReturnVO;
                case "column":
                    List<ModuleEntity> moduleList2 = moduleService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList2 = new ArrayList<>();
                    if (!StringUtils.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId2 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList2 = moduleList2.stream().filter(t -> moduleId2.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleColumnEntity> moduleColumnList = columnService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    dataReturnVO = this.moduleColumn(selectList2, moduleColumnList, list, authorizeModel);
                    return dataReturnVO;
                case "resource":
                    List<ModuleEntity> moduleList3 = moduleService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList3 = new ArrayList<>();
                    if (!StringUtils.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId3 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList3 = moduleList3.stream().filter(t -> moduleId3.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleDataAuthorizeSchemeEntity> moduleDataSchemeList = schemeService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    dataReturnVO = this.resourceData(selectList3, moduleDataSchemeList, list, authorizeModel);
                    return dataReturnVO;
                case "form":
                    List<ModuleEntity> moduleList4 = moduleService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList4 = new ArrayList<>();
                    if (!StringUtils.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId4 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList4 = moduleList4.stream().filter(t -> moduleId4.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleFormEntity> moduleFormList = formService.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    dataReturnVO = this.moduleForm(selectList4, moduleFormList, list, authorizeModel);
                    return dataReturnVO;
                case "userList":
                    List<UserEntity> userEntityList = userService.getUserListByRoleId(objectId);
                    dataReturnVO = this.roleUserList(userEntityList);
                    return dataReturnVO;
                default:
            }
        }
        return dataReturnVO;
    }

    /**
     * 功能权限
     *
     * @param moduleListAll  所有功能
     * @param authorizeList  已有权限
     * @param authorizeModel 权限集合
     * @return
     */
    @Override
    public AuthorizeDataReturnVO module(List<ModuleEntity> moduleListAll, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        List<ModuleModel> moduleList = authorizeModel.getModuleList();
        List<String> moduleModeId = moduleListAll.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> ids = authorizeList.stream().filter(t -> "module".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        moduleModeId.addAll(ids);
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<AuthorizeDataModel> treeList = JsonUtil.getJsonToList(moduleList, AuthorizeDataModel.class);
        List<SumTree<AuthorizeDataModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
            moduleModeId.add("1");
        }
        vo.setAll(moduleModeId);
        vo.setIds(ids);
        vo.setList(dataList);
        return vo;
    }

    /**
     * 按钮权限
     *
     * @param moduleList     功能
     * @param moduleButton   按钮
     * @param authorizeList  已有权限
     * @param authorizeModel 权限集合
     * @return
     */
    @Override
    public AuthorizeDataReturnVO moduleButton(List<ModuleEntity> moduleList, List<ModuleButtonEntity> moduleButton, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ButtonModel> buttonList = authorizeModel.getButtonList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> buttonModeId = buttonList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(buttonModeId);
        List<String> ids = authorizeList.stream().filter(t -> "button".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ButtonModel buttonModel : buttonList) {
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(buttonModel.getId());
            treeModel.setFullName(buttonModel.getFullName());
            treeModel.setParentId(buttonModel.getModuleId());
            treeModel.setIcon(buttonModel.getIcon());
            treeList.add(treeModel);
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> buttonModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        vo.setAll(moduleModeId);
        vo.setIds(ids);
        vo.setList(dataList);
        return vo;
    }

    /**
     * 列表权限
     *
     * @param moduleList       功能
     * @param moduleColumnList 列表
     * @param authorizeList    已有权限
     * @param authorizeModel   权限集合
     * @return
     */
    @Override
    public AuthorizeDataReturnVO moduleColumn(List<ModuleEntity> moduleList, List<ModuleColumnEntity> moduleColumnList, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ColumnModel> columnList = authorizeModel.getColumnList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> columnModeId = columnList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(columnModeId);
        List<String> ids = authorizeList.stream().filter(t -> "column".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ColumnModel columnModel : columnList) {
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(columnModel.getId());
            treeModel.setFullName(columnModel.getFullName());
            treeModel.setParentId(columnModel.getModuleId());
            treeModel.setIcon("fa fa-tags column");
            treeList.add(treeModel);
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> columnModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        vo.setAll(moduleModeId);
        vo.setIds(ids);
        vo.setList(dataList);
        return vo;
    }

    /**
     * 表单权限
     *
     * @param moduleList     功能
     * @param moduleFormList 表单列表
     * @param authorizeList  已有权限
     * @param authorizeModel 权限集合
     * @return
     */
    @Override
    public AuthorizeDataReturnVO moduleForm(List<ModuleEntity> moduleList, List<ModuleFormEntity> moduleFormList, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ModuleFormModel> formList = authorizeModel.getFormsList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> formModeId = formList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(formModeId);
        List<String> ids = authorizeList.stream().filter(t -> "form".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ModuleFormModel columnModel : formList) {
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(columnModel.getId());
            treeModel.setFullName(columnModel.getFullName());
            treeModel.setParentId(columnModel.getModuleId());
            treeModel.setIcon("fa fa-binoculars resource");
            treeList.add(treeModel);
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> formModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        vo.setAll(moduleModeId);
        vo.setIds(ids);
        vo.setList(dataList);
        return vo;
    }

    /**
     * 数据权限
     *
     * @param moduleList           功能
     * @param moduleDataSchemeList 数据方案
     * @param authorizeList        已有权限
     * @param authorizeModel       权限集合
     * @return
     */
    @Override
    public AuthorizeDataReturnVO resourceData(List<ModuleEntity> moduleList, List<ModuleDataAuthorizeSchemeEntity> moduleDataSchemeList, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ResourceModel> resourceList = authorizeModel.getResourceList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> resourceModeId = resourceList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(resourceModeId);
        List<String> ids = authorizeList.stream().filter(t -> "resource".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ResourceModel resourceModel : resourceList) {
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(resourceModel.getId());
            treeModel.setFullName(resourceModel.getFullName());
            treeModel.setParentId(resourceModel.getModuleId());
            treeModel.setIcon("fa fa-binoculars resource");
            treeList.add(treeModel);
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> resourceModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        vo.setAll(moduleModeId);
        vo.setIds(ids);
        vo.setList(dataList);
        return vo;
    }

    /**
     * 用户列表数据转换
     *
     * @param userEntityList 用户列表
     * @return
     */
    private AuthorizeDataReturnVO roleUserList(List<UserEntity> userEntityList) {
        AuthorizeDataReturnVO dataReturnVO = new AuthorizeDataReturnVO();
        List<AuthorizeDataReturnModel> userList = new ArrayList<>();
        for (UserEntity userEntity : userEntityList) {
            AuthorizeDataReturnModel authorizeDataReturnModel = new AuthorizeDataReturnModel();
            authorizeDataReturnModel.setId(userEntity.getId());
            authorizeDataReturnModel.setFullName(userEntity.getRealName());
            userList.add(authorizeDataReturnModel);
        }
        dataReturnVO.setList(userList);
        return dataReturnVO;
    }
}
